package com.bbh.plugin.single.privilege.demo.directive;

import com.bbh.common.domain.MenuResult;
import com.bbh.common.freemarker.directive.BaseDirective;
import com.bbh.common.utils.Exceptions;
import com.bbh.common.utils.web.spring.SpringUtils;
import freemarker.core.Environment;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.config.shiro.base.entity.Principal;
import org.springframework.boot.config.shiro.base.service.ShiroAccountService;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Map;

/**
 * Created by roman_000 on 2015/10/20.
 */
@Component("principalDirective1")
public class PrincipalDirective extends BaseDirective {
    private Logger logger = LoggerFactory.getLogger(PrincipalDirective.class);
    private static final String VARIABLE_NAME = "principal";

    public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) throws TemplateException, IOException {
        Subject subject = SecurityUtils.getSubject();
        Principal principal = (Principal) subject.getPrincipal();
        ShiroAccountService shiroAccountService = null;
        try {
            Object menus = subject.getSession().getAttribute("menus");
            if (menus != null) {
                principal.setMenuResult((MenuResult) menus);
            } else {
                shiroAccountService = SpringUtils.getBean("shiroAccountServiceImpl", ShiroAccountService.class);
                principal.setMenuResult((shiroAccountService.findMenuListByLoginName( principal.getLoginName())));
            }
        } catch (Exception ex) {
            logger.error(Exceptions.getStackTraceAsString(ex));
        }
        setLocalVariable(VARIABLE_NAME, principal, env, body);
    }
}
